#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "stdlib.h"
#include "string.h"
#include "sys/ioctl.h"
#include "sys/time.h"
#include "poll.h"
#include "sys/select.h"


int main(int argc, char *argv[]){
	int fd;
	int ret;
	unsigned char data;
	char *filename;
	struct pollfd fds;
	fd_set readfds;
	struct timeval timeout;

	if (argc != 2) {
		printf("Error Usage!\r\n");
		return -1;
	}
	
	filename = argv[1];
	fd = open(filename, O_RDWR | O_NONBLOCK);
	if(fd < 0) {
		printf("file %s open failed\r\n",filename);
		return -1;
	}
#if 0
	while (1)
	{
		ret = read(fd, &data, sizeof(data));
		if (ret<0)
		{
				
		}else{
			if(data){
				printf("keyvalue = %#X\r\n", data);
			}
		}
		
	}
#endif

	while(1){
		FD_ZERO(&readfds);
		FD_SET(fd, &readfds);
		/* 构造超时时间 */
		timeout.tv_sec = 0;
		timeout.tv_usec = 500000; /* 500ms */
		ret = select(fd + 1, &readfds, NULL, NULL, &timeout);
		switch (ret)
		{
		case 0:
			/* 用户自定义超时处理 */
			// printf("超时！！！\r\n");
			break;

		case -1:
			/* 用户自定义错误处理 */
			break;
				
		default:
			if(FD_ISSET(fd,&readfds)){
				ret = read(fd, &data, sizeof(data));
				if(ret < 0){
					/* 读取错误 */
				}else {
					if(data){
						printf("key value=%#x\r\n", data);
					}
				}
			}
			break;
		}
	}

	ret = close(fd);  // close文件
	if(ret <0){
		printf("file %s close failed\r\n",argv[1]);
		return -1;
	}

	return 0;
}
